package wonderful.com.oneminute.activity;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ListView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;

import wonderful.com.oneminute.R;
import wonderful.com.oneminute.adapter.JokeAdapter;
import wonderful.com.oneminute.entity.Joke;
import wonderful.com.oneminute.utils.Contans;
import wonderful.com.oneminute.utils.HttpUtils;

public class JokeActivity extends Activity {

    ArrayList<Joke> jokedata = new ArrayList<>();
    Handler handler = new Handler();
    private JokeAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_joke);
        //准备数据源
        initData();
        //初始化ListView
        initView();
    }

    private void initData() {

        new Thread() {
            @Override
            public void run() {
                getJoke(Contans.getJokeUrl());
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        adapter.notifyDataSetChanged();
                    }
                });
            }
        }.start();

    }

    public void getJoke(String url) {

        String json = HttpUtils.loadStringFromURL(url);
        if (json != null) {
            JSONObject jsonObject = JSON.parseObject(json);
            JSONArray result = jsonObject.getJSONArray("result");
            for (Object o : result) {
                String s = o.toString();
                Joke joke = JSONObject.parseObject(s, Joke.class);
                jokedata.add(joke);

            }
        }
    }

    private void initView() {

        ListView listv = (ListView) findViewById(R.id.JokeListView);
        //设置适配器
        adapter = new JokeAdapter(jokedata, getBaseContext());
        listv.setAdapter(adapter);
    }

}
